<template>
  <div v-if="!loading" class="customer-card">
    <el-menu
      :default-active = "defaultActive"
      @select="handleSelect"
      :router="active">
      <el-menu-item
      class="card"
      style="padding: 0"
      v-for="(item, index) in cardListTrans"
      :index="handleSplit(item._id, index)"
      :key="item._id"
      :class="{'custom-is-active': $route.path.split('/')[4] === item._id}">
        <div class="cust-type">
          <label class="fake-checkbox" :class="{'visible': batch[tabType].isBatchShow}" v-on:click.stop="">
            <input type="checkbox" class="fbox" :value="item._id" v-model.trim="item.checked" @change="checkThis(item.checked)">
            <span></span>
            <i class="fake-label"></i>
          </label>
          <!-- <span class="ct">
              <customer-avatar :status="item.status" type="customer" :isRead="item.isRead && item.owner === agentId?true:false" :paddingSize="8" :size="24"></customer-avatar>
          </span> -->
        </div>
        <dl class="cust_name" :class="tabType==='customer_plan' ? 'plan' : ''">
            <dt>{{ item.name }}</dt>
            <dd :class="['date', notifyTimeClass(item.notifyTime)]"
                  v-if="tabType==='customer_plan'">
            <!-- {{item.notifyTime.split(':')[0]}}:{{item.notifyTime.split(':')[1]}} -->
            {{item.cardTime}}
          </dd>
            <dd v-if="tabType==='customer_all'" class="cust-all-owner">{{custOwner(item)}}</dd>
        </dl>
        <dl class="cust_remark">
          <dt v-if="tabType==='customer_plan'" class="action">{{item.action || $t('public.noResult')}}</dt>
          <dt v-else class="action">{{item.title || $t('public.noResult')}}</dt>
          <dd v-if="tabType==='customer_plan'" :class="['cust-status']" v-statusColor="item.status">{{status(item.status)}}</dd>
          <dd class="cust-allmy-content" v-else v-statusColor="item.status">
            {{status(item.status)}}
          </dd>
        </dl>
        <span class="unread-circle" v-show="tabType === 'customer_my' && (item.isRead && item.owner === agentId?true:false)"></span>
        <!--<div class="isRead" v-show="item.isRead && item.owner === agentId || item.isImport"></div>-->
        <!-- <div :class="['info', tabType==='customer_plan'?'cust-plan__info':'']">
          <ul>
            <li><h4>{{ item.name }}</h4></li>
            <li v-if="tabType==='customer_plan'"><span class="action">{{item.action || $t('public.noResult')}}</span></li>
            <li v-else><span class="action">{{item.title || $t('public.noResult')}}</span></li>
          </ul>
        </div>
        <div :class="['remark', tabType==='customer_plan'?'remark__paln':'']">
          <span :class="['date', notifyTimeClass(item.notifyTime)]"
                v-if="tabType==='customer_plan'">
          {{item.notifyTime.split(':')[0]}}:{{item.notifyTime.split(':')[1]}}</span>
          <span v-if="tabType==='customer_plan'" :class="['cust-status']" v-statusColor="item.status">{{status(item.status)}}</span>
          <div class="cust-allmy-content" v-else>
              <span v-if="tabType==='customer_all'" class="cust-all-owner">{{custOwner(item)}}</span>
              <span :class="['cust-status']" v-statusColor="item.status">{{status(item.status)}}</span>
          </div>
        </div> -->
      </el-menu-item>
    </el-menu>
    <no-record v-if="cardList && cardList.length<=0"></no-record>
  <!-- 批处理开始 -->
    <div class="batch_cover" :class="{'navMenuState': navMenuState}" v-show="batch[tabType].isBatchShow"></div>
    <div class="batch_btm" v-show="batch[tabType].isBatchShow"></div>
    <div class="batch" :class="{'show': batch[tabType].isBatchShow, 'navMenuState': navMenuState}">
      <el-checkbox v-model.trim="batch[tabType].allChecked" @change="checkAll()">{{$t('public.checkAll')}}</el-checkbox>
      <card-batch v-if="batch[tabType].operator"
      :tabType="tabType"
      :batchOperator="batch[tabType]"
      @checkNone="checkNone"
      @deleteCustomer="deleteCustomer"
      @exportCustomer="exportCustomer"
      @exportCustomerCdr="exportCustomerCdr"
      @exportBatchMonitor="exportBatchMonitor"
      @cancelCustomerContactPlan="cancelCustomerContactPlan"
      @editStatus="editStatus"
      @custConvert="custConvert"
      @assignCustomer="assignCustomer"
      ></card-batch>
    </div>
    <el-dialog :close-on-click-modal="false" modal-append-to-body :title="$t('call.selfDefineName')" :visible.sync="defineDialogForm" width="50%">
      <el-form>
        <el-input
          type="text"
          :rows="2"
          placeholder=""
          style="width:100%"
          v-model="defaultName">
        </el-input>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" class="primary_btn" @click="confirmDownloadMonitor">{{$t('public.confirm')}}</el-button>
      </div>
    </el-dialog>
    <update-status-dialog
      :isUpStaDialog = "isUpStaDialog"
      @cancelAndSubmit="upStaDialogClose"
      :count="batchCount"
    >
    </update-status-dialog>
    <customer-conversion
      :isCusCvDialog = "isCusCvDialog"
      @cancelAndSubmit="cusCvDialogClose"
      :count="batchCount"
    ></customer-conversion>
    <assign-customer
      :isAssignDialog = "isAssignDialog"
      @cancelAndSubmit="assignDialogClose"
      :count="batchCount"
    >
    </assign-customer>
    <ExportDialog :isShow="exportDialogIsShow"
                  ref="ExportDialog"
                  :isHiddenAssociate="true"
                  :exportDialogTitle="exportDialogTitle"
                  :exportHeads="exportHeads"
                  :isExportTask="isExportTask"
                  :isCall="false"
                  @exportDialogCancelFun="exportDialogCancelFun"
                  @exportDialogDefineFun="exportDialogDefineFun"
                  v-if="exportDialogIsShow"></ExportDialog>
  <!-- 批处理结束 -->
  </div>
</template>
<script>
  import { statusCustColorArr } from '@/utils/reportUtils'
  import ExportDialog from '@/components/public-modules/export/exportDialog'
  // import CustomerAvatar from '@/components/ui-modules/customer-avatar/CustomerAvatar'
  import CardBatch from '@/components/public-modules/card/CardBatch'
  import { isNotAllowEditCustomerInfo, isAllowDeleteCustomer, isAllowExportCustomer, isAllowAssignCustomer, isNotAllowEditStatus, isAllowConvertCustomer, isAllowExportCustomerCdr, isAllowExportBatchMonitor, getNotifyDate } from '@/utils/customerUtils.js'
  import UpdateStatusDialog from './UpdateStatusDialog'
  import CustomerConversion from './CustomerConversion'
  import NoRecord from '@/components/public-modules/card/NoRecord'
  import AssignCustomer from './AssignCustomer'
  import { timeFormat, dateParse, deepClone } from '@/utils/m7Utils.js'
  export default {
    name: 'CustomerCard',
    props: {
      allCount: Number,
      qu: Object,
      cardList: Array,
      type: String,
      tabType: String,
      clearChecked: String,
      count: Number,
      condition: Object
    },
    data () {
      return {
        flag: this.$store.getters.isEcommerce ? 'ecommerce' : 'kf',
        exportHeads: [],
        cusFieldArr: [],
        isExportTask: false,
        exportDialogIsShow: false,
        agents: null,
        custCategorys: null,
        // 批处理更新客户状态模态框出现的控制
        isUpStaDialog: false,
        // 批处理转移客户模态框
        isCusCvDialog: false,
        isAssignDialog: false,
        batchCount: 0,
        loading: true,
        active: true,
        defaultActive: '',
        dbType: '',
        batch: {
          customer_my: {
            batchItem: [],
            allChecked: false,
            isBatchShow: false,
            checkedCount: 0,
            operator: []
          },
          customer_plan: {
            batchItem: [],
            allChecked: false,
            isBatchShow: false,
            checkedCount: 0,
            operator: []
          },
          customer_all: {
            batchItem: [],
            allChecked: false,
            isBatchShow: false,
            checkedCount: 0,
            operator: []
          }
        },
        defineDialogForm: false,
        defaultName: '',
        queryData: '',
        exportTaskLimit: {},
        exportDialogTitle: '',
        exportObj: {
          exportFun: null,
          data: null,
          count: 0,
          type: ''
        },
        statusColors: statusCustColorArr
      }
    },
    watch: {
      cardList () {
        this.defaultActive = this.$route.path
      },
      // clearChecked 变化 再次执行
      clearChecked: 'checkNone'
    },
    components: {
      ExportDialog,
      // CustomerAvatar,
      CardBatch,
      UpdateStatusDialog,
      CustomerConversion,
      NoRecord,
      AssignCustomer
    },
    computed: {
      agentId () {
        return this.$store.state.session.user._id
      },
      cardListTrans () {
        for (let i = 0; i < this.cardList.length; i++) {
          let item = this.cardList[i]
          item.cardTime = timeFormat(item.notifyTime, 'card')
        }
        return this.cardList
      },
      navMenuState () {
        return this.$store.state.navMenuState || false
      }
    },
    methods: {
      exportCustomer () {
        this.exportDialogTitle = '导出客户'
        this.exportHeads = deepClone(this.cusFieldArr)
        this.exportObj.type = 'customerExport'
        this.exportObj.count = 0
        if (this.batch[this.tabType].allChecked) {
          this.queryCustomerListCount(this.$store, this.activeName, this.qu).then((resp) => {
            if (resp.success) {
              this.exportDialogIsShow = true
              const _count = resp.count
              let exportFun = 'exportCustomer'
              let data = {
                Method: 'exportCustomer2In',
                Query: {
                  dbType: this.dbType,
                  menu: this.tabType
                }
              }
              if (_count > this.exportTaskLimit.customer) {
                this.$message({
                  type: 'error',
                  message: this.$t('customer.exportCustomerOver1000000', {exportTaskLimit: this.exportTaskLimit.customer})
                })
                return
              }
              if (_count > 10000) {
                data.Method = 'exportCustomer'
                exportFun = 'exportCustomerMore'
                this.isExportTask = true
              }
              Object.assign(data.Query, this.transferData(this.condition))
              this.exportObj.data = data
              this.exportObj.exportFun = exportFun
              this.exportObj.count = _count
            }
          })
        } else {
          let exportFun = 'exportCustomer'
          let data = {
            Method: 'exportCustomer2In',
            Query: {
              dbType: this.dbType,
              menu: this.tabType
            }
          }
          this.exportDialogIsShow = true
          let ids = this.getChecked()
          data.Query._id = { $in: ids }
          this.exportObj.data = data
          this.exportObj.exportFun = exportFun
//          this.$store.dispatch(exportFun, data).then(() => {
//            this.checkNone()
//          })
        }
      },
      exportDialogCancelFun () {
        this.exportDialogIsShow = false
      },
      exportDialogDefineFun (obj) {
        console.log(obj)
        if (this.exportObj.type === 'customerExport') {
          let exportFun = this.exportObj.exportFun
          let _count = this.exportObj.count
          let data = this.exportObj.data
          data.Query.headers = obj.checkedExportHeads || []
          if (data.Method === 'exportCustomer') {
            data.Query.note = obj.textarea
          }
          this.$store.dispatch(exportFun, data).then(() => {
            this.exportDialogIsShow = false
            if (this.batch[this.tabType].allChecked && _count > 10000) {
              this.$message({
                type: 'success',
                dangerouslyUseHTMLString: true,
                message: this.$t('customer.exportCustomerOver10000', {moreOperation: '<span class="iconfont icon-gengduo"></span>'})
              })
            }
            // 成功后重置批量选择
            this.checkNone()
          })
        }
      },
      queryCustomerListCount (store, tabName, query) {
        return store.dispatch('queryCustomerListCount', query)
      },
      notifyTimeClass (date) {
        return getNotifyDate(date).type
      },
      // 按照 卡片的_id不同设置不同路由
      handleSplit (_id, index) {
        return '/index/' + this.type + '/' + this.tabType + '/' + _id + '?cardIndex=' + index
      },
      handleSelect (index) {
        let cardIndex = index.split('cardIndex=')[1] || ''
        if (cardIndex) {
          // 已阅读的客户卡片去除红点标记
          let item = this.cardList[cardIndex]
          item.isRead = false
          this.cardList.splice(cardIndex, 1, item)
        }
        this.$store.commit('customer/REFRESH_CUST_RIGHT', Math.random())
      },
      status (status) {
        // let cs = this.$store.state.session.dicMap.custTmpls[0].status[status]
        let custTmpls = this.$getCache('custTmpls')
        if (status && custTmpls[0]) {
          let cs = custTmpls[0].status[status]
          if (cs) {
            return cs
          } else {
            return this.$t('customer.deleteStatus')
          }
        } else {
          return ''
        }
      },
      custOwner (item) {
        if (this.tabType !== 'customer_all') return ''
        let agent = this.agents[item.owner]
        if (agent) {
          return agent.displayName
        } else {
          for (let i = 0; i < this.custCategorys.length; i++) {
            if (this.custCategorys[i]._id === item.categoryId) {
              return this.custCategorys[i].cName.split('[')[0]
            }
          }
        }
        return this.$t('customer.noOwner')
      },
      getChecked () { // 单选获取数组
        return this.cardList.filter(item => item.checked).map(item => item._id)
      },
      checkThis (checked) { // 单个选中传送数组和展示批量
        let checkedArr = this.getChecked()
        let isBatchShow = checkedArr.length > 0
        this.batch[this.tabType].allChecked = checkedArr.length === this.$store.state.customer.customerList[this.tabType].count
        this.batch[this.tabType].batchItem = checkedArr
        this.batch[this.tabType].isBatchShow = isBatchShow
        this.batch[this.tabType].checkedCount = checkedArr.length
      },
      checkAll () { // 全选&取消全选
        this.batch[this.tabType].isBatchShow = this.batch[this.tabType].allChecked
        let inputs = this.$el.getElementsByClassName('fbox')
        this.cardList.forEach((item) => {
          item.checked = this.batch[this.tabType].allChecked
        })
        for (let i = 0; i < inputs.length; i++) { // 升级之后有bug需要手动将checkbox调整为相应状态
          inputs[i].checked = this.batch[this.tabType].allChecked
        }
        if (this.$store.state.customer.customerList[this.tabType].more) {
          this.batch[this.tabType].checkedCount = this.batch[this.tabType].allChecked ? '多于' + this.$store.state.customer.customerList[this.tabType].count : 0
        } else {
          if (this.allCount) {
            this.batch[this.tabType].checkedCount = this.allCount
          } else {
            this.batch[this.tabType].checkedCount = this.batch[this.tabType].allChecked ? this.$store.state.customer.customerList[this.tabType].count : 0
          }
        }
      },
      checkNone () {
        this.batch[this.tabType].allChecked = false
        this.batch[this.tabType].batchItem = []
        this.batch[this.tabType].isBatchShow = false
        this.cardList.forEach((item) => {
          item.checked = false
        })
      },
      transferData (condition) {
        let data = {}
        for (let key in condition) {
          if (
            condition[key] && (
              condition[key].length > 0 ||
              (condition[key].$in && condition[key].$in.length)
            )
          ) {
            data[key] = condition[key]
          }
        }
        delete data.page
        delete data.limit
        return data
      },
      handleDeleteCustomer (count, data) {
        let deleteCustomerMessageWithLength = 'customer.deleteCustomerMessageWithLength'
        if (count > 500) {
          deleteCustomerMessageWithLength = 'customer.deleteCustomerMessageWithLength500'
          if (count > 5000) {
            deleteCustomerMessageWithLength = 'customer.deleteCustomerMessageWithLength10000'
          }
          this.delConfirm({
            confirmCentent: deleteCustomerMessageWithLength,
            confirmTitle: 'customer.deleteCustomerRemindOne',
            data: data,
            count,
            del: 'customer.deleteCustomerMessageOne',
            flag: 'next'
          }).then(val => {
            if (!val) {
              this.delConfirm({
                confirmCentent: deleteCustomerMessageWithLength,
                confirmTitle: 'customer.deleteCustomerRemindTwo',
                data: data,
                count: count,
                del: 'customer.deleteCustomerMessageTwo',
                btn: 'customer.deleteCustomerButtonTwo',
                flag: 'next'
              }).then(val => {
                if (!val) {
                  this.delConfirm({
                    confirmCentent: deleteCustomerMessageWithLength,
                    confirmTitle: 'customer.deleteCustomerRemindThree',
                    data: data,
                    count: count,
                    del: 'customer.deleteCustomerMessageThree',
                    btn: 'customer.deleteCustomerButtonThree',
                    flag: 'lastConfirm'
                  })
                }
              })
            }
          })
        } else {
          this.delConfirm({
            confirmCentent: deleteCustomerMessageWithLength,
            confirmTitle: 'customer.deleteCustomer',
            data: data,
            count: count,
            del: 'customer.deleteCustomerMessageOne',
            flag: 'lastConfirm'
          })
        }
      },
      deleteCustomer () {
        if (this.batch[this.tabType].allChecked) {
          this.queryCustomerListCount(this.$store, this.activeName, this.qu).then((resp) => {
            if (resp.success) {
              const _count = resp.count
              let data = {
                dbType: this.dbType
              }
              let count
              Object.assign(data, this.transferData(this.condition))
              count = _count
              this.handleDeleteCustomer(count, data)
            }
          })
        } else {
          let data = {
            dbType: this.dbType
          }
          let count
          let ids = this.getChecked()
          data._id = { $in: ids }
          count = ids.length
          this.handleDeleteCustomer(count, data)
        }
      },
      delConfirm (data) {
        return this.$confirm(this.$t(data.confirmCentent, { length: data.count, next: this.$t(data.del) }), this.$t(data.confirmTitle), {
          confirmButtonText: this.$t(data.btn) || this.$t('public.confirm'),
          cancelButtonText: this.$t('public.cancel'),
          cancelButtonClass: 'primary_btn',
          confirmButtonClass: 'primary_btn',
          type: 'warning'
        }).then((v) => {
          if (data.flag !== 'lastConfirm') {
            return false
          } else {
            return this.$store.dispatch('deleteCustomer', data.data).then(() => {
              // 成功后重置批量选择
              this.$emit('allCountClear')
              this.checkNone()
              this.$store.commit('customer/EMPTY_RIGHT')
              this.$message({
                type: 'success',
                message: this.$t('customer.deleteCustomerSuccess')
              })
            })
          }
        }).catch((err) => {
          if (err === 'cancel') {
            return 'cancel'
          }
        })
      },
      editStatus () {
        if (this.batch[this.tabType].allChecked) {
          this.queryCustomerListCount(this.$store, this.activeName, this.qu).then((resp) => {
            if (resp.success) {
              const _count = resp.count
              if (_count > 10000) {
                this.$message({
                  type: 'error',
                  message: this.$t('customer.batchUpdateOver10000')
                })
                return
              }
              this.batchCount = _count
              this.isUpStaDialog = !this.isUpStaDialog
            }
          })
        } else {
          let ids = this.getChecked()
          this.batchCount = ids.length
          this.isUpStaDialog = !this.isUpStaDialog
        }
      },
      upStaDialogClose (obj) {
        if (obj.type === 'cancel' || obj.type === 'close') {
          this.isUpStaDialog = obj.bool
          return
        }

        let data = {
          query: {
            dbType: this.dbType
          },
          status: obj.status,
          total: this.batchCount
        }

        if (this.batch[this.tabType].allChecked) {
          Object.assign(data.query, this.transferData(this.condition))
        } else {
          let ids = this.getChecked()
          data.query._id = { $in: ids }
        }
        this.$store.dispatch('batchUpdateCustomerStatus', data).then(() => {
          this.isUpStaDialog = obj.bool
          this.checkNone()
        })
      },
      custConvert () {
        if (this.batch[this.tabType].allChecked) {
          this.queryCustomerListCount(this.$store, this.activeName, this.qu).then((resp) => {
            if (resp.success) {
              const _count = resp.count
              if (_count > 10000) {
                this.$message({
                  type: 'error',
                  message: this.$t('customer.batchUpdateOver10000')
                })
                return
              }
              this.batchCount = _count
              this.isCusCvDialog = !this.isCusCvDialog
            }
          })
        } else {
          let ids = this.getChecked()
          this.batchCount = ids.length
          this.isCusCvDialog = !this.isCusCvDialog
        }
      },
      cusCvDialogClose (obj) {
        if (obj.type === 'cancel' || obj.type === 'close') {
          this.isCusCvDialog = obj.bool
          return
        }

        let data = {
          query: {
            dbType: this.dbType
          },
          categoryId: obj.categoryId,
          total: this.batchCount
        }

        if (this.batch[this.tabType].allChecked) {
          Object.assign(data.query, this.transferData(this.condition))
        } else {
          let ids = this.getChecked()
          data.query._id = { $in: ids }
        }
        this.$store.dispatch('batchUpdateCustomerCategory', data).then(() => {
          this.isCusCvDialog = obj.bool
          this.$emit('allCountClear')
          this.checkNone()
          this.$router.push('/index/customer')
        })
      },
      assignCustomer () {
        if (this.batch[this.tabType].allChecked) {
          this.queryCustomerListCount(this.$store, this.activeName, this.qu).then((resp) => {
            if (resp.success) {
              const _count = resp.count
              if (_count > 10000) {
                this.batchCount = 10000
              } else {
                this.batchCount = _count
              }
              this.isAssignDialog = !this.isAssignDialog
            }
          })
        } else {
          let ids = this.getChecked()
          this.batchCount = ids.length
          this.isAssignDialog = !this.isAssignDialog
        }
      },
      assignDialogClose (obj) {
        if (obj.type === 'cancel' || obj.type === 'close') {
          this.isAssignDialog = obj.bool
          return
        }

        let data = {
          query: {
            dbType: this.dbType
          },
          owners: obj.owners
        }

        if (this.batch[this.tabType].allChecked) {
          Object.assign(data.query, this.transferData(this.condition))
          data.total = this.batchCount
        } else {
          let ids = this.getChecked()
          data.query._id = { $in: ids }
          data.total = ids.length
        }

        this.$store.dispatch('assignCustomer', data).then(() => {
          this.isAssignDialog = obj.bool
          // 成功后重置批量选择
          this.$emit('allCountClear')
          this.checkNone()
        })
      },
      exportCustomerCdr () {
        if (this.batch[this.tabType].allChecked) {
          this.queryCustomerListCount(this.$store, this.activeName, this.qu).then((resp) => {
            if (resp.success) {
              const _count = resp.count
              let data = {
                Method: 'exportCustomerCdr',
                Query: {
                  dbType: this.dbType,
                  menu: this.tabType
                }
              }
              Object.assign(data.Query, this.transferData(this.condition))
              if (_count > 1000 && _count <= this.exportTaskLimit.customerCdr_customer) { // 导出通话记录大于1000时走任务,上限50000
                this.toCallSheetTask(data)
                return
              } else if (_count > this.exportTaskLimit.customerCdr_customer) {
                this.$message({
                  type: 'error',
                  message: '最多导出' + this.exportTaskLimit.customerCdr_customer + '个客户的通话记录,请过滤查询条件分多次导出。'
                })
                return
              }
              this.hanldeExportCustomerCdr(data)
            }
          })
        } else {
          let data = {
            Method: 'exportCustomerCdr',
            Query: {
              dbType: this.dbType,
              menu: this.tabType
            }
          }
          let ids = this.getChecked()
          data.Query._id = { $in: ids }
          this.hanldeExportCustomerCdr(data)
        }
      },
      hanldeExportCustomerCdr (data) {
        data.isKf = true // kf请求这个接口，后台会把上限改成5W的通话记录，否则还是原来的1000
        this.$store.dispatch('exportCustomerCdr', data).then((res) => {
          if (res.success) {
            // 成功后重置批量选择
            this.checkNone()
          } else {
            if (res.callSheetCount) {
              if (res.callSheetCount <= this.exportTaskLimit.customerCdr_call) {
                data.isKf && delete data.isKf
                this.toCallSheetTask(data)
              } else if (res.callSheetCount > this.exportTaskLimit.customerCdr_call) {
                this.$message({
                  type: 'error',
                  message: '通话详情超过' + this.exportTaskLimit.customerCdr_call + '条上限，请过滤查询条件！'
                })
              }
            }
          }
        })
      },
      toCallSheetTask (data) {
        let actionData = data.Query
        this.$store.dispatch('addCustomerCdrExportTask', actionData).then(resp => {
          if (resp && resp.success) {
            this.$message({
              type: 'success',
              message: this.$t('call.exportCustomerCallSheetTaskSuccess')
            })
            // 成功后重置批量选择
            this.checkNone()
          } else {
            if (resp && resp.message.indexOf('export_task_max_limit') > -1) {
              this.$message({
                type: 'error',
                message: this.$t('message.export_task_max_limit')
              })
            } else {
              this.$message({
                type: 'error',
                message: this.$t('message.export_task_max_error')
              })
            }
          }
        })
      },
      exportBatchMonitor () {
        if (this.batch[this.tabType].allChecked) {
          this.queryCustomerListCount(this.$store, this.activeName, this.qu).then((resp) => {
            if (resp.success) {
              const _count = resp.count
              let data = {
                dbType: this.dbType
              }
              if (_count > 10000) {
                this.$message({
                  type: 'error',
                  message: this.$t('customer.exportMonitorTaskOver10000')
                })
                return
              }
              Object.assign(data, this.transferData(this.condition))
              data.checkRecordExist = true
              this.queryData = data
              this.handleAddCustomerExportMonitorTask(data)
            }
          })
        } else {
          let data = {
            dbType: this.dbType
          }
          let ids = this.getChecked()
          data._id = { $in: ids }
          data.checkRecordExist = true
          this.queryData = data
          this.handleAddCustomerExportMonitorTask(data)
        }
      },
      handleAddCustomerExportMonitorTask (data) {
        this.$store.dispatch('addCustomerExportMonitorTask', data).then(rep => {
          if (rep.success) {
            let num = ''
            for (let i = 0; i < 19; i++) {
              num += Math.floor(Math.random() * 10).toString()
            }
            let name = this.$store.state.session.user.account + '_' + this.$store.state.session.user.pbx + '_' + num
            this.defaultName = name
            this.defineDialogForm = true
          } else if (rep.message === 'expired_record_exists') {
            this.$message.error(this.$t('call.exportOverLimit', {recordStore: rep.recordStore, validStartDate: rep.validStartDate}))
          }
        })
      },
      confirmDownloadMonitor () {
        let data = this.queryData
        delete data.checkRecordExist
        // data.fileName = new Date().getFullYear().toString() + (new Date().getMonth() + 1).toString() + new Date().getDate().toString() + '_' + this.defaultName.trim().replace(/\s/g, '')
        data.fileName = dateParse(new Date()).split('-').join('') + '_' + this.defaultName.trim().replace(/\s/g, '')
        if (!(/^[\u4E00-\u9FA5a-zA-Z0-9_.-]*$/).test(data.fileName)) {
          this.$message.error(this.$t('call.symbolForbid'))
          return
        }
        this.defineDialogForm = false
        this.$store.dispatch('addCustomerExportMonitorTask', data).then(rep => {
          if (rep.success) {
            this.$message({
              message: this.$t('call.exportMonitorTaskSuccess'),
              type: 'success'
            })
            this.checkNone()
          }
        })
      },
      cancelContactPlanMessageWithLength (count, data) {
        this.$confirm(this.$t('customer.cancelContactPlanMessageWithLength', { length: count }), this.$t('public.cancelPlan'), {
          confirmButtonText: this.$t('public.confirm'),
          cancelButtonText: this.$t('public.cancel'),
          cancelButtonClass: 'primary_btn',
          confirmButtonClass: 'primary_btn',
          type: 'warning'
        }).then((v) => {
          return this.$store.dispatch('cancelCustomerContactPlan', data).then(() => {
            // 成功后重置批量选择
            this.$emit('allCountClear')
            this.checkNone()
            this.$store.commit('customer/EMPTY_RIGHT')
          })
        }).catch(err => {
          if (err === 'cancel') {}
        })
      },
      cancelCustomerContactPlan () {
        if (this.batch[this.tabType].allChecked) {
          this.queryCustomerListCount(this.$store, this.activeName, this.qu).then((resp) => {
            if (resp.success) {
              const _count = resp.count
              let data, count
              if (_count > 10000) {
                this.$message({
                  type: 'error',
                  message: this.$t('customer.batchUpdateOver10000')
                })
                return
              }
              data = {
                query: {},
                total: _count
              }
              count = _count
              Object.assign(data.query, this.transferData(this.condition))
              this.cancelContactPlanMessageWithLength(count, data)
            }
          })
        } else {
          let data, count
          let ids = this.getChecked()
          data = {
            query: {
              _id: { $in: ids }
            },
            total: ids.length
          }
          count = ids.length
          this.cancelContactPlanMessageWithLength(count, data)
        }
      }
    },
    directives: { // 自定义指令 改变文字color的值
      statusColor: {
        inserted (el, binding, vnode) {
          let self = vnode.context
          let custTmpls = self.$getCache('custTmpls')
          let statusConfig = {}
          if (custTmpls && custTmpls[0]) {
            statusConfig = custTmpls[0].statusConfig
          }
          // let statusConfig = self.$store.state.session.dicMap.custTmpls[0].statusConfig || {}
          if (binding.value) {
            if (statusConfig && statusConfig[binding.value]) {
              el.style.color = statusConfig[binding.value].color
            } else {
              el.style.color = self.statusColors[binding.value] ? self.statusColors[binding.value] : '#009FE3'
            }
          }
        },
        update (el, binding, vnode) {
          let self = vnode.context
          let custTmpls = self.$getCache('custTmpls')
          let statusConfig = {}
          if (custTmpls && custTmpls[0]) {
            statusConfig = custTmpls[0].statusConfig
          }
          // let statusConfig = self.$store.state.session.dicMap.custTmpls[0].statusConfig || {}
          if (binding.value) {
            if (statusConfig && statusConfig[binding.value]) {
              el.style.color = statusConfig[binding.value].color
            } else {
              el.style.color = self.statusColors[binding.value] ? self.statusColors[binding.value] : '#009FE3'
            }
          }
        }
      }
    },
    beforeMount () {
      this.exportTaskLimit = this.$getCache('exportTaskLimit') || {}
      let p1 = this.$store.dispatch('getCache', {type: 'custTmpls'})
      let p2 = this.$store.dispatch('getCache', { type: 'agents' })
      let p3 = this.$store.dispatch('getCache', { type: 'custCategorys' })
      Promise.all([p1, p2, p3]).then(([custTmpls, agents, custCategorys]) => {
        let user = this.$store.state.session.user
        let batchOperators = []
        if (!isNotAllowEditCustomerInfo(user) && isAllowDeleteCustomer(user)) {
          batchOperators.push({ name: 'public.delete', class: 'icon-shanchu', action: 'deleteCustomer' })
        }
        if (isAllowExportCustomer(user)) {
          batchOperators.push({ name: 'public.export', class: 'icon-daochu1', action: 'exportCustomer' })
        }
        if (!isNotAllowEditCustomerInfo(user) && isAllowAssignCustomer(user)) {
          batchOperators.push({ name: 'public.assign', class: 'icon-fenpei', action: 'assignCustomer' })
        }
        if (!isNotAllowEditCustomerInfo(user) && !isNotAllowEditStatus(user)) {
          batchOperators.push({ name: 'public.editStatus', class: 'icon-beizhu', action: 'editStatus' })
        }
        if (!isNotAllowEditCustomerInfo(user) && isAllowConvertCustomer(user)) {
          batchOperators.push({ name: 'public.custConvert', class: 'icon-zhuanhuan', action: 'custConvert' })
        }
        if (isAllowExportCustomerCdr(user)) {
          batchOperators.push({ name: 'public.exportCALL', class: 'icon-daochutonghuajilu', action: 'exportCustomerCdr' })
        }
        if (isAllowExportBatchMonitor(user)) {
          batchOperators.push({ name: 'public.exportTask', class: 'icon-piliang', action: 'exportBatchMonitor' })
        }
        batchOperators.push({ name: 'public.cancelPlan', class: 'icon-quxiaolianxijihua', action: 'cancelCustomerContactPlan' })
//        for (let key in this.batch) {
//          this.batch[key].operator = batchOperators
//        }
        for (let key in this.batch) {
          if (key !== 'customer_plan') {
            this.batch[key].operator = batchOperators
          } else {
            this.batch[key].operator = [{ name: 'public.cancelPlan', class: 'icon-quxiaolianxijihua', action: 'cancelCustomerContactPlan' }]
          }
        }
        if (custTmpls.length <= 0) { // 新开的账户，没有数据
          return
        }
        let stableFields = custTmpls[0].stable_fields || []
        for (let i = 0; i < stableFields.length; i++) {
          if (!stableFields[i].isShow) {
            this.cusFieldArr.push({
              name: stableFields[i].name,
              value: stableFields[i].value
            })
          }
        }
        let _arr = [
          { name: 'owner',
            value: this.$t('customer.ownerPeople')
          },
          {
            name: 'ownerNo',
            value: this.$t('webchat.exportHead.agentNum')
          },
          // {
          //   name: 'taskId',
          //   value: this.$t('webchat.exportHead.outcallTask')
          // },
          // {
          //   name: 'taskCalled',
          //   value: this.$t('webchat.exportHead.dialState')
          // },
          {
            name: 'status',
            value: this.$t('webchat.exportHead.custStatus')
          },
          {
            name: 'source',
            value: this.$t('customer.dataSource')
          },
          {
            name: 'creator',
            value: this.$t('public.creator')
          },
          {
            name: 'createTime',
            value: this.$t('webchat.createTime')
          },
          {
            name: 'lastUpdateTime',
            value: this.$t('monitor.updateTime')
          },
          {
            name: 'attachs',
            value: this.$t('public.attach')
          },
          {
            name: 'sysStatus',
            value: this.$t('customer.sysStatus')
          },
          {
            name: 'categoryId',
            value: this.$t('customer.categoryId')
          },
          {
            name: 'customFields',
            value: this.$t('customer.customField')
          }
        ]
        if (this.flag !== 'ecommerce') {
          _arr.push({name: 'taskId', value: this.$t('webchat.exportHead.outcallTask')})
          _arr.push({name: 'taskCalled', value: this.$t('webchat.exportHead.dialState')})
        }
        this.cusFieldArr = [...this.cusFieldArr, ..._arr]
        this.dbType = custTmpls[0]._id
        this.agents = this.$store.getters.agents || {}
        this.custCategorys = custCategorys
        this.loading = false
      })
    }
  }
</script>
<style lang="stylus" scoped>
@import "../../../assets/common.styl"
.unread-circle
  background-color: #f56c6c;
  border-radius: 10px;
  width: 10px;
  height: 10px;
  position: absolute;
  top: 12px;
  right: 10px;
.customer-card
  height 100%
.el-menu-item
  height auto
  line-height inherit
  padding 0
.el-menu-item.custom-is-active
  background-color $c-card-active
.card:hover
  background-color $c-card-hover
.card:active
  label
    visibility visible
/*.el-checkbox
  visibility hidden*/
.e-ch-show
  visibility visible
/*label
  visibility hidden*/
.visible
  visibility visible
.card
  width 100%
  height 60px
  border-bottom 1px solid $c-border1
  background-color $cf-white
  /*display flex*/
  cursor pointer
  padding 0
  .cust-type
    /*display flex*/
    margin 0 10px
    align-items center
    .el-checkbox
      visibility hidden
    .e-ch-show
      visibility visible
    .ct
      display inline-block
      position relative
      margin 0 auto
  .info
    /*flex 1*/
    float left
    padding-top 7px
    margin 0 10px 0 20px
    width calc(100% - 40px - 8em)
    li
      margin-bottom 2px
      h4
        text-overflow ellipsis
        overflow hidden
        white-space nowrap
        font-weight 400
        max-width 12em
        padding-bottom 2px
        color $cf-gray0
      span
        display block
        text-overflow ellipsis
        overflow hidden
        white-space nowrap
        max-width 100%
        color $cf-gray3
  // flex 设为1 其他两个固定是自动张开填充
  .cust-plan__info
    /*flex 1*/
    li
      h4, span
        max-width 100%
  .remark
    /*display flex*/
    float right
    padding-top 8px
    color $cf-gray4
    /*flex-direction column*/
    margin-right 8px
    /*align-items flex-end*/
    .cust-allmy-content
      /*display flex
      flex-direction column*/
      /*float right*/
      text-align right
      .cust-all-owner
        display inline-block
        margin-bottom 6px
        /*max-width 6em*/
        text-overflow ellipsis
        overflow hidden
        white-space nowrap
    .date
      width 100%
      line-height 20px
      margin-bottom 2px
    .usable
      color $cf-level2
  .cust_name
    display flex
    padding 7px 10px 0px 25px
    overflow hidden
    line-height 22px
    justify-content space-between
    dt
      flex-shrink 1
      /*max-width calc(300px - 5em)*/
      overflow hidden
      font-weight bold
      text-overflow ellipsis
      color $cf-gray2
      font-size 14px
    dd
      max-width 7em
      margin-left 5px
      overflow hidden
      text-overflow ellipsis
      flex-shrink 0
      align-items flex-end
      text-align right
      color $cf-gray6
  .plan
    dt
      flex-shrink 1
      max-width calc(300px - 1em)
      color $cf-gray2
    dd
      flex-shrink 0
      max-width 11em
      color $cf-gray5
    .overdue
      color #ff6b6b
    .today-action
      color #ff8403
  .cust_remark
    display flex
    padding 0px 10px 0 25px
    overflow hidden
    justify-content space-between
    dt
      flex-shrink 1
      /*max-width calc(300px - 5em)*/
      overflow hidden
      text-overflow ellipsis
    dd
      max-width 7em
      margin-left 5px
      overflow hidden
      text-overflow ellipsis
      flex-shrink 0
      align-items flex-end
      color $cf-gray4
    .action
      color $cf-gray4
.visible .fake-label
  height 60px
  margin: -12px 0 0 -9px;
.fake-checkbox
  margin-left 1px
/*.cust-status
  margin-bottom 6px
  max-width 6em
  display block
  @extend .ellipsis*/
/*.cust-status0*/
  /*color #9761AD*/
/*.cust-status1*/
  /*color #ED5870*/
/*.cust-status2*/
  /*color #F48C4D*/
/*.cust-status3*/
  /*color #FBB100*/
/*.cust-status4*/
  /*color #79B05D*/
/*.cust-status5*/
  /*color #5F89BB*/
/*.cust-status6*/
  /*color #66BDC7*/
/*.cust-status7*/
  /*color #9761AD*/
/*.cust-status8*/
  /*color #BBC9D6*/
/*.cust-status9*/
  /*color #CECECE*/
.remark__paln
  text-align right
.isRead
  position: absolute
  left: 8px
  top: 33px
  width: 10px
  height: 10px
  border-radius: 50%
  background-color: $c-pink
.hidden
  visibility hidden
</style>
